package com.technology.education.wxapi

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.technology.education.data.AppData
import com.technology.education.ext.getAppViewModel
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory

class WXPayEntryActivity : AppCompatActivity(), IWXAPIEventHandler {
    private var api: IWXAPI? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        api = WXAPIFactory.createWXAPI(this, AppData.WX_ID)
        api?.handleIntent(intent, this)
    }
    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        api?.handleIntent(intent,this)
    }

    override fun onReq(p0: BaseReq?) {

    }

    override fun onResp(resp: BaseResp) {
        if (resp.type == ConstantsAPI.COMMAND_PAY_BY_WX) {
            when (resp.errCode) {
                0 -> {
                    getAppViewModel().wechatPayResult.postValue(true)
                }
                -2 -> Toast.makeText(this, "取消支付！", Toast.LENGTH_LONG).show()
                -1 -> Toast.makeText(this, "支付失败！", Toast.LENGTH_LONG).show()
                else -> Toast.makeText(this, "支付出错！", Toast.LENGTH_LONG).show()
            }
        }
        finish()
    }
}